import React from 'react';
import ReactDom from 'react-dom';

// let ThemeContext = React.createContext();
function createContext(initalValue) {
    class Provider extends React.Component {
        //作为静态属性存到Provider的类上，通过类名可以调用到这个属性
        static contextValue = initalValue;

        constructor(props) {
            super(props);
            // this.state = {};
            Provider.contextValue = props.value
        }

        static getDerivedStateFromProps(nextProps, prevState) {
            //更新后的value值赋给contextValue
            Provider.contextValue = nextProps.value;
        }

        render() {
            return (
                this.props.children

            );
        }
    }

    class Consumer extends React.Component {
        render() {
            return this.props.children(Provider.contextValue);
        }
    }

    return {Provider, Consumer}

}

let ThemeContext = createContext(null);


class Ttile extends React.Component {
    //指定contextType =等于定义的上下文
    static contextType = ThemeContext;

    render() {
        return (
            <div style={{border: `5px solid ${this.context.color}`}}>
                title
            </div>
        )
    }
}


//class：
class Header extends React.Component {
    //指定contextType =等于定义的上下文
    static contextType = ThemeContext;

    render() {
        return (
            <div style={{border: `5px solid ${this.context.color}`}}>
                header
                <Title/>
            </div>
        )
    }
}


class Content extends React.Component {
    static contextType = ThemeContext;

    render() {
        return (
            <div style={{border: `5px solid ${this.context.color}`}}>
                <button onClick={() => this.context.changeColor('blue')}>change blue</button>
                <button onClick={() => this.context.changeColor('red')}>change red</button>
            </div>
        );
    }

}


class Main extends React.Component {
    static contextType = ThemeContext;

    render() {
        return (
            <div style={{border: `5px solid ${this.context.color}`}}>
                main
                <Content/>
            </div>
        );
    }
}


class Panel extends React.Component {
    state = {color: 'green'};

    changeColor = (color) => {
        this.setState({color: color})

    };

    render() {
        let value = {color: this.state.color, changeColor: this.changeColor};
        //Provider提供者，他负责向下层的所有的组件提供数据value:前提是value里面必须包含我们需要的函数或者变量等值，其他组件才可以接收到
        return (

            <ThemeContext.Provider value={value}>
                <div style={{border: `5px solid ${this.state.color}`, width: 500}}>
                    panel
                    <Header/>
                    <Main/>
                </div>
            </ThemeContext.Provider>

        )
    }
}

ReactDom.render(<Panel/>, document.getElementById('root'));
